<template>
    <el-container class="app_container flex">
        <Aside @handleNodeClick="handleNodeClick" />
        <el-main class="app_main flex">
            <Breadcrumb :title="pageTitle" />
            <div class="app_content">
                <el-form ref="searchForm" :model="searchMap">
                    <div class="serach_wrapper flex-space-between el-form--inline">
                        <div class="search flex">
                            <el-form-item prop="riskName" size="small">
                                <el-input v-model="searchMap.riskName" placeholder="请输入风险源名称"></el-input>
                            </el-form-item>
                            <el-form-item class="flex">
                                <el-button @click="handleSearch()" class="btn_primary">查询</el-button>
                                <el-button @click="handleReset()" class="btn_cancel">重置</el-button>
                            </el-form-item>
                        </div>
                        <div class="edit">
                            <el-form-item class="flex">
                                <el-button @click="handleAdd()" class="btn_primary el-icon-plus">新增</el-button>
                            </el-form-item>
                        </div>
                    </div>
                </el-form>
                <el-table class="per_table" style="width: 100%" :data="dataList" v-loading="loading" stripe
                    :height="winTableH">
                    <el-table-column prop="deptName" label="所属单位" fixed width="200px"></el-table-column>
                    <el-table-column prop="riskName" label="风险源名称" width="200px"></el-table-column>
                    <el-table-column prop="riskCode" label="风险源编码" align="center"></el-table-column>
                    <el-table-column prop="riskType" label="风险源类型" align="center">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.risk_source_type" :value="scope.row.riskType" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="riskFactor" label="风险因素" align="center"></el-table-column>
                    <el-table-column prop="riskDes" label="风险描述" align="center" width="200px"></el-table-column>
                    <el-table-column prop="accidentPossibility" label="事故发生的可能性" align="center">
                    </el-table-column>
                    <el-table-column prop="frequencyExposure" label="暴露于危险环境" align="center">
                    </el-table-column>
                    <el-table-column prop="accidentSeriousness" label="发生事故事件" align="center">
                    </el-table-column>
                    <el-table-column prop="sort" label="风险值" align="center">
                        <template slot-scope="scope">
                            {{ parseNumberOrReturnOne(scope.row.accidentPossibility) *
                                parseNumberOrReturnOne(scope.row.frequencyExposure) *
                                parseNumberOrReturnOne(scope.row.accidentSeriousness) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="riskLevel" label="风险源等级" align="center" width="100px">
                        <template slot-scope="scope">
                            <dict-tag :options="dict.type.risk_level" :value="scope.row.riskLevel" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="riskLevel" label="风险源颜色" align="center" width="100px">
                        <template slot-scope="scope">
                            <span class="table-span-color-box" v-if="scope.row.riskLevel === '1'"
                                style="background-color:red;"></span>
                            <span class="table-span-color-box" v-else-if="scope.row.riskLevel === '2'"
                                style="background-color:orange;"></span>
                            <span class="table-span-color-box" v-else-if="scope.row.riskLevel === '3'"
                                style="background-color:#2A3394"></span>
                            <span class="table-span-color-box" v-else style="background-color:#67C23A;"></span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="riskDetailAddress" label="地址" align="center"></el-table-column>
                    <el-table-column label="操作" width="470" fixed="right">
                        <template slot-scope="scope">
                            <div>
                                <span type="text" class="tag_primary" size="small"
                                    @click="handleSelect(scope.row)">查看</span>
                                <span type="text" class="tag_primary marginl-10" size="small"
                                    @click="handleEdit(scope.row)">编辑</span>
                                <span type="text" class="tag_warning marginl-10" size="small"
                                    @click="handleDelete(scope.row)">删除</span>
                                <span type="text" class="tag_primary marginl-10" size="small"
                                    @click="handleIdentify(scope.row)">风险识别任务</span>
                                <span type="text" class="tag_primary marginl-10" size="small"
                                    @click="handleAssess(scope.row)">风险动态评估</span>
                                <span type="text" class="tag_primary marginl-10" size="small"
                                    @click="handleControl(scope.row)">风险管控</span>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <Pagination v-show="total > 0" :total="total" :page.sync="searchMap.pageNum"
                    :limit.sync="searchMap.pageSize" @change="getList"></Pagination>
            </div>
            <!-- 弹窗 详情 -->
            <el-dialog class="m_dialog" :title="title" :visible.sync="dialogVisible" width="800" append-to-body
                :before-close="() => { dialogVisible = false }" :close-on-click-modal="false">
                <div class="content">
                    <el-form ref="form" :key="reqType" :model="formModel" size="small" :rules="formRules"
                        label-width="80px">
                        <el-row :gutter="20" v-if="title === '风险动态评估'">
                            <el-col :span="24">
                                <el-form-item label="风险因素" label-width="120px" prop="riskFactor">
                                    <el-input v-model="formModel.riskFactor" placeholder="请输入风险因素"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="风险描述" label-width="120px" prop="riskDes">
                                    <el-input v-model="formModel.riskDes" type="textarea" placeholder="请输入风险描述"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="可能性(L)" label-width="120px" prop="accidentPossibility">
                                    <el-select v-model="formModel.accidentPossibility" placeholder="请选择"
                                        style="width: 100%;" @change="checkAndPerformAction">
                                        <el-option v-for="(item, index) in dict.type.accident_possibility"
                                            :label="item.label" :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="频繁程度(E)" label-width="120px" prop="frequencyExposure">
                                    <el-select v-model="formModel.frequencyExposure" placeholder="请选择" style="width: 100%;"
                                        @change="checkAndPerformAction">
                                        <el-option v-for="(item, index) in dict.type.frequency_exposure" :label="item.label"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="严重性(C)" label-width="120px" prop="accidentSeriousness">
                                    <el-select v-model="formModel.accidentSeriousness" placeholder="请选择"
                                        style="width: 100%;" @change="checkAndPerformAction">
                                        <el-option v-for="(item, index) in dict.type.accident_seriousness"
                                            :label="item.label" :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <p style="color: #fff;margin-left: 30px;">风险值: {{
                                    (parseNumberOrReturnOne(formModel.accidentPossibility) *
                                        parseNumberOrReturnOne(formModel.frequencyExposure) *
                                        parseNumberOrReturnOne(formModel.accidentSeriousness)).toFixed(2) }}</p>
                            </el-col>
                            <el-col :span="24">
                                <p style="color: #fff;">评价级别 <span
                                        style="display: inline-block; margin-left: 10px;margin-top: 30px;"><dict-tag
                                            :options="dict.type.risk_level" :value="riskObj.level" /></span></p>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20" v-if="title === '风险管控'">
                            <el-col :span="24">
                                <el-form-item label="管控措施名称" label-width="120px" prop="riskControlMeasuresIds">
                                    <el-select v-model="formModel.riskControlMeasuresIds" multiple placeholder="请选择"
                                        style="width: 100%;" @change="controlSelectChange">
                                        <el-option v-for="(item, index) in controlDataList"
                                            :label="item.riskControlMeasuresTitle"
                                            :value="item.riskControlMeasuresId"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="管控措施内容" label-width="120px" prop="remarkCount">
                                    <el-input v-model="remarkCount" type="textarea" placeholder="请输入"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row :gutter="20" v-if="title !== '风险管控' && title !== '风险动态评估'">
                            <el-col :span="24">
                                <el-form-item label="单位" label-width="120px" prop="deptId">
                                    <treeselect v-model="formModel.deptId" :options="deptOptions" :show-count="true"
                                        placeholder="请选择" @input="treeselectInput" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="风险源名称" label-width="120px" prop="riskName">
                                    <el-input v-model="formModel.riskName" placeholder="请输入风险源名称"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="风险源编码" label-width="120px" prop="riskCode">
                                    <el-input v-model="formModel.riskCode" placeholder="请输入风险源编码"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="风险源类型" label-width="120px" prop="riskType">
                                    <el-select v-model="formModel.riskType" placeholder="请选择" style="width: 100%;">
                                        <el-option v-for="(item, index) in dict.type.risk_source_type" :label="item.label"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="风险源等级" label-width="120px" prop="riskLevel">
                                    <el-select v-model="formModel.riskLevel" placeholder="请选择" style="width: 100%;">
                                        <el-option v-for="(item, index) in dict.type.risk_level" :label="item.label"
                                            :value="item.value"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="风险点" label-width="120px" prop="riskDetailAddress">
                                    <el-select v-model="formModel.riskLevelName" placeholder="请选择平面图"
                                        @change="selectChange">
                                        <el-option v-for="item in picList" :key="item.projectPointPicId"
                                            :label="item.picName" :value="item.projectPointPicId">
                                        </el-option>
                                    </el-select>
                                    <el-button :disabled="false" @click="imageAnnotation()" type="primary">标注</el-button>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="详细地址" label-width="120px" prop="riskDetailAddress">
                                    <el-input v-model="formModel.riskDetailAddress" placeholder="请输入详细地址"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="备注" label-width="120px">
                                    <el-input v-model="formModel.remark" type="textarea" placeholder="请输入备注"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="() => { dialogVisible = false }" class="btn_cancel">取 消</el-button>
                    <el-button type="primary" @click="submitFrom()" class="btn_primary">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 地图弹窗 -->
            <el-dialog class="m_dialog" title="请选择经纬度" :visible.sync="isVisibleMap" width="800" append-to-body
                :before-close="() => { isVisibleMap = false }" :close-on-click-modal="false">
                <div class="content" style="position: relative">
                    <div class="mapDiv" ref="map" :key="mapKey" style="width: 100%; height: 466px"></div>
                    <div class="map-Contern">
                        <el-form class="map-form" size="small" ref="mapForm" :model="mapForm" label-width="0">
                            <el-form-item label="">
                                <el-input v-model="mapForm.mapSearch" placeholder="搜索地区">
                                    <template slot="suffix">
                                        <i class="el-icon-search" @click="mapSearchFn"></i>
                                    </template>
                                </el-input>
                            </el-form-item>
                            <el-form-item label="">
                                <span style="color: #8fabbf">经纬度</span>
                                <el-input v-model="mapForm.maplnglat" placeholder=""> </el-input>
                            </el-form-item>
                            <el-form-item label="">
                                <span style="color: #8fabbf">地址</span>
                                <el-input v-model="mapForm.mapaddress" placeholder="请选择地址"></el-input>
                            </el-form-item>
                        </el-form>
                        <div slot="footer" class="map-footer-btn">
                            <el-button @click="() => { isVisibleMap = false }" class="btn_cancel">取 消</el-button>
                            <el-button type="primary" @click="mapSubmitForm" class="btn_primary">确 定</el-button>
                        </div>
                    </div>
                </div>
            </el-dialog>
            <el-dialog class="m_dialog" title="标注" :visible.sync="markDialogVisible" width="800" append-to-body
                :close-on-click-modal="false">
                <PlanPosition2 :formData="positionData" :pictrue="pictrue" @setPosition="getPosition"
                    :key="planPositionKey"></PlanPosition2>
            </el-dialog>
            <el-dialog title="风险点详情" :visible.sync="dialogVisibleInfo" width="800" append-to-body>
                <custom-title title="详细信息" />
                <BaseDescriptions :descConfig="descConfig" :descConfigItem="descConfigItem" :descModel="formModel">
                    <template #riskType>
                        <dict-tag :options="dict.type.risk_source_type" :value="formModel.riskType" />
                    </template>
                    <template #riskLevel>
                        <dict-tag :options="dict.type.risk_level" :value="formModel.riskLevel" />
                    </template>
                    <template #riskLevelName>
                        <el-button @click="imageAnnotation('slot')" type="small">标注</el-button>
                    </template>
                </BaseDescriptions>
            </el-dialog>
        </el-main>
    </el-container>
</template>
<script>
import request from "@/utils/request";
import { delProjectPointRisk, listProjectPointRisk, projectPointRiskRiskDynamicEval, projectPointRiskLevelCalc, projectPointRiskRiskControlMeasures, riskControlMeasuresList } from '../api/index'
import { listUser, deptTreeSelect, userDeptTreeSelect } from '@/api'
import { getProjectPointPicList } from '@/api/projectPoints/projectImg.js'
import Aside from '@/components/Aside'
import { EventBus } from '@/utils/eventbus';
import BaseDescriptions from '@/components/PageContent/BaseDescriptions.vue';

import Map from "ol/Map";
import View from "ol/View";
import XYZ from "ol/source/XYZ";
import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import PlanPosition from '../../system/project/riskPoint/PlanPosition.vue'
import PlanPosition2 from '../../system/project/riskPoint/PlanPosition2.vue'
import { Circle, Fill, Icon, Stroke, Style, Text } from "ol/style.js";
import { OGCMapTile, Vector as VectorSource } from "ol/source.js";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";

export default {
    dicts: ['risk_level', 'device_communicate_type', 'risk_source_type', 'accident_possibility', 'frequency_exposure', 'accident_seriousness'],
    data() {
        return {
            pageTitle: '风险点',
            picKey: 0,
            src: '',
            picList: [],
            pictrue: {},
            positionData: {
                positionX: 0,
                positionY: 0,
            },
            rowPosition: [],
            remarkCount: '',
            loading: true,
            total: 0,
            title: '新增风险点',
            dialogVisible: false,
            markDialogVisible: false,
            dialogVisibleInfo: false,
            deptOptions: undefined,
            reqType: 'post',
            projectPointId: '',
            // 地图表单
            mapForm: {
                mapSearch: undefined,
                maplnglat: undefined,
                mapaddress: undefined,
            },
            // 是否可见地图
            isVisibleMap: false,
            // 地图
            map: null,
            // 天地图token
            mapToken: "f01023d9e7977aa8946e0137daf05a2b",
            // 地图矢量图层源
            vectorSource: undefined,
            // 地图点位图片样式
            iconStyle: undefined,
            controlDataList: [],
            searchMap: {
                pageNum: 1,
                pageSize: 10,
            },
            dataList: [],
            // 提交表单数据
            formModel: {},
            formRules: {
                deptId: {
                    required: true,
                    message: "所属单位不能为空",
                    trigger: "change",
                },
                riskName: {
                    required: true,
                    message: "风险源名称不能为空",
                    trigger: "change",
                },
                riskCode: {
                    required: true,
                    message: "风险源编码不能为空",
                    trigger: "change",
                },
                riskType: {
                    required: true,
                    message: "风险源类型不能为空",
                    trigger: "change",
                },
                riskLevel: {
                    required: true,
                    message: "风险源等级不能为空",
                    trigger: "change",
                },
                location: {
                    required: true,
                    message: "风险源地点不能为空",
                    trigger: "change",
                },
                detailedAddress: {
                    required: true,
                    message: "详细地址不能为空",
                    trigger: "change",
                },
                lng: {
                    required: true,
                    message: "经度不能为空",
                    trigger: "change",
                },
                lat: {
                    required: true,
                    message: "纬度不能为空",
                    trigger: "change",
                },
                riskFactor: {
                    required: true,
                    message: "风险因素不能为空",
                    trigger: "change",
                },
                accidentPossibility: {
                    required: true,
                    message: "事故可能性不能为空",
                    trigger: "change",
                },
                frequencyExposure: {
                    required: true,
                    message: "频繁程度不能为空",
                    trigger: "change",
                },
                accidentSeriousness: {
                    required: true,
                    message: "事故严重性不能为空",
                    trigger: "change",
                },
            },
            riskObj: {
                value: '',
                level: '',
            },
            mapKey: 0,
            planPositionKey: 0,
            tempPosition: undefined,
            descConfig: {
                size: 'medium',
                column: '2',
            },
            descConfigItem: [
                {
                    fieIdName: 'deptName',
                    label: '单位',
                    span: 2,
                },
                {
                    fieIdName: 'riskName',
                    label: '风险源名称',
                    span: 2,
                },
                {
                    fieIdName: 'riskCode',
                    label: '风险源编码',
                    span: 2,
                },
                {
                    fieIdName: 'riskType',
                    label: '风险源类型',
                    span: 2,
                    slotName: 'riskType',
                },
                {
                    fieIdName: 'riskLevel',
                    label: '风险源等级',
                    span: 12,
                    slotName: 'riskType',
                },
                {
                    fieIdName: 'riskLevelName',
                    label: '风险点',
                    span: 12,
                    slotName: 'riskLevelName',
                },
                {
                    fieIdName: 'remark',
                    label: '备注',
                    span: 12,
                },
            ],
        }
    },
    components: { Aside, PlanPosition, PlanPosition2, BaseDescriptions },
    watch: {
        formModel: {
            deep: true,
            handler() {
            },
        },
    },
    methods: {
        //编辑
        handleEdit(row) {
            this.title = "编辑风险点"
            this.reqType = 'put'
            this.dialogDataFilter(row)

            setTimeout(() => {
                this.dialogVisible = true;
            }, 300);
        },
        //查看
        handleSelect(row) {
            this.reqType = 'select'
            this.dialogDataFilter(row)
            setTimeout(() => {
                this.dialogVisibleInfo = true;
            }, 200);
        },
        dialogDataFilter(row) {
            this.src = ''
            this.formModel.riskLevelName = ''
            this.$set(this, 'formModel', JSON.parse(JSON.stringify(row)))
            this.getPicList()
            console.log(row)
            if (row.positions && row.positions.length > 0) {
                this.positionData.positionX = row.positions[0].x | 0
                this.positionData.positionY = row.positions[0].y | 0
                console.log(this.positionData, '默认坐标')
            }
            console.log(row.projectPointPicId)
            setTimeout(() => {
                const found = this.picList.some(item => item.projectPointPicId === row.projectPointPicId);
                console.log('1', this.picList)
                if (found) {
                    this.picList.forEach(item => {
                        if (item.projectPointPicId === row.projectPointPicId) {
                            this.formModel.riskLevelName = item.picName
                            this.src = this.$store.state.config.inFilePrefix + item.picUrl
                        }
                    })
                    console.log('2')
                } else {
                    console.log('3')
                    this.src = ''
                }
                this.planPositionKey += 1
            }, 500);

        },
        getPosition(val) {
            this.tempPosition = val
        },
        //新增打开
        handleAdd() {
            this.title = "新增风险点"
            this.reqType = 'post'
            if (this.$refs.form) {
                this.$refs.form.resetFields()
            }
            this.formModel = {}
            this.src = ''
            this.dialogVisible = true;
        },
        submitFrom() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    const operationMap = {
                        "风险动态评估": projectPointRiskRiskDynamicEval,
                        "风险管控": projectPointRiskRiskControlMeasures,
                        "默认操作": delProjectPointRisk
                    };
                    const selectedOperation = operationMap[this.title] || operationMap["默认操作"];
                    console.log(this.formModel, '入参')
                    console.log(this.tempPosition, '坐标')
                    let params = {
                        ...this.formModel,
                        positions: this.tempPosition ? [{ x: this.tempPosition.positionX | 0, y: this.tempPosition.positionY | 0 }] : [],
                    }
                    selectedOperation(params, this.reqType)
                        .then(res => {
                            if (res.code === 200) {
                                this.$message.success('操作成功');
                                this.dialogVisible = false;
                                this.getList();
                            }
                        });

                } else {
                    return false;
                }
            });
        },
        //删除
        handleDelete(row) {
            this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                delProjectPointRisk([row.projectPointRiskId], 'delete').then(res => {
                    if (200 === res.code) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getList()
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        // 风险识别任务
        handleIdentify(row) {
            // console.log(row)
            this.$router.push({
                path: './riskTask',
                query: {
                    projectPointId: row.projectPointId,
                    projectPointRiskId: row.projectPointRiskId
                }
            })
        },
        // 风险动态评估
        handleAssess(row) {
            this.title = "风险动态评估"
            this.formModel = row
            console.log(row)
            this.riskObj.level = row.riskLevel
            this.riskObj.value = ''
            this.reqType = 'put'
            this.dialogVisible = true;
        },
        // 风险管控
        handleControl(row) {
            this.title = "风险管控"
            this.reqType = 'post'
            // this.formModel = row
            this.formModel.projectPointRiskId = row.projectPointRiskId
            this.dialogVisible = true;

            this.getControlList(row.deptId)



        },
        // 页面数据
        async getList() {
            const { code, rows, total } = await listProjectPointRisk(this.searchMap)
            // console.log(code, rows)
            if (code === 200) {
                this.loading = false
                this.dataList = rows
                this.total = total
                // console.log(this.dataList)
            }
        },
        // 管控数据
        async getControlList(id) {
            let params = {
                pageNum: 1,
                pageSize: 10,
                deptId: id
            }
            const { code, rows, total } = await riskControlMeasuresList(params)
            if (code === 200) {
                console.log(rows)
                this.controlDataList = rows
                this.formModel.riskControlMeasuresIds = []
                this.remarkCount = ''
            }
        },
        controlSelectChange(val) {
            console.log(val)
            this.remarkCount = ''
            this.controlDataList.forEach(item => {
                val.forEach(item2 => {
                    if (item.riskControlMeasuresId === item2) {
                        this.remarkCount += '，' + item.riskControlMeasuresContent
                    }
                })
            })
            this.remarkCount = this.remarkCount.substring(1)
        },
        // 节点点击触发
        handleNodeClick(treeData) {
            console.log(treeData, '节点触发')
            this.searchMap.deptId = treeData.id
            this.formModel.projectPointId = treeData.projectPointId
            this.projectPointId = treeData.projectPointId
            this.getList();
        },
        treeselectInput(val) {
            console.log(val, '单位信息')
            this.formModel.deptName = this.findNodeById(this.deptOptions, val).label
            this.formModel.projectPointId = this.findNodeById(this.deptOptions, val).projectPointId
            // console.log(this.findNodeById(this.deptOptions, val))
            this.getPicList()
            // this.getControlList()
        },
        findNodeById(nodes, id) {
            for (let i = 0; i < nodes.length; i++) {
                const node = nodes[i];
                if (node.id === id) {
                    return node;
                }
                if (node.children) {
                    const foundNode = this.findNodeById(node.children, id);
                    if (foundNode) {
                        return foundNode;
                    }
                }
            }
            return null;
        },
        //查询项目点下拉树
        async initPostTree() {
            this.isShowTree = false
            await userDeptTreeSelect().then(res => {
                console.log(res)
            })
        },
        /** 查询部门下拉树结构 */
        getDeptTree() {
            userDeptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        handleGetCoordinates(val) {
            const coordinatesArray = val.split(',').map(str => parseInt(str.trim(), 10));
            // console.log(coordinatesArray)

            this.formModel.positions = coordinatesArray

            // console.log(val, '坐标')
        },
        // 标注弹窗
        imageAnnotation(slot) {
            if (slot === 'slot') {
                if (!this.src) {
                    return this.$message.error('暂无标注')
                }
            } else {
                if (!this.src) {
                    return this.$message.error('请先选择一张图片')
                }
            }
            this.picKey += 1
            this.$set(this.pictrue, 'picUrl', this.src)
            this.markDialogVisible = true;
        },
        cancel() {
            this.markDialogVisible = false;
        },
        //选择平面图
        selectChange(id) {
            // console.log(id, 'picItem')
            const selectedOption = this.picList.find(item => item.projectPointPicId === id);
            // console.log('Selected option:', selectedOption);
            this.formModel.projectPointPicId = selectedOption.projectPointPicId
            this.src = this.$store.state.config.inFilePrefix + selectedOption.picUrl
        },
        //获取平面图列表
        getPicList() {
            getProjectPointPicList({ picType: 1, projectPointId: this.formModel.projectPointId }).then(res => {
                this.picList = res.rows
                console.log(res, 'pic list')
            })
        },
        checkAndPerformAction() {
            if (this.formModel.accidentPossibility &&
                this.formModel.frequencyExposure &&
                this.formModel.accidentSeriousness) {
                // 所有字段都有值，执行你的操作
                this.getProjectPointRiskLevelCalc();
            }
        },
        getProjectPointRiskLevelCalc() {
            let params = {
                accidentPossibility: this.formModel.accidentPossibility,
                accidentSeriousness: this.formModel.accidentSeriousness,
                frequencyExposure: this.formModel.frequencyExposure,
            }
            projectPointRiskLevelCalc(params).then(res => {
                // console.log(res)
                this.riskObj.value = res.data.riskValue
                this.riskObj.level = res.data.riskLevel
            })
        },
        // 查询
        handleSearch() {
            this.getList()
        },
        // 重置
        handleReset() {
            this.searchMap = {
                pageNum: 1,
                pageSize: 10,
            }
            this.getList()
        },
        parseNumberOrReturnOne(value) {
            const number = Number(value);
            return isNaN(number) ? 1 : number;
        },
        selectCoordinate() {
            this.isVisibleMap = true;
            (this.mapForm = {
                mapSearch: undefined,
                maplnglat: undefined,
                mapaddress: undefined,
            }),
                this.initMap();
            // 初始化 Map 并在 Vue 组件的 mounted 钩子中设置它
        },
        // 地图初始化
        initMap() {
            this.mapKey += 1
            this.$nextTick(() => {
                // 创建一个矢量要素
                const iconFeature = new Feature({
                    geometry: new Point([118.1163, 24.4673]),
                });
                // 定义图片样式
                this.iconStyle = new Style({
                    image: new Icon({
                        anchor: [0.5, 1],
                        src: "https://openlayers.org/en/latest/examples/data/icon.png",
                    }),
                });
                // 设置要素样式
                iconFeature.setStyle(this.iconStyle);

                // 创建矢量数据源和图层
                this.vectorSource = new VectorSource({
                    features: [iconFeature],
                });
                const vectorLayer = new VectorLayer({
                    source: this.vectorSource,
                });
                this.map = new Map({
                    layers: [
                        new TileLayer({
                            source: new XYZ({
                                url: `http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
                            }),
                            // setStyle: "black",
                        }),
                        new TileLayer({
                            source: new XYZ({
                                url: `http://t0.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
                            }),
                            // setStyle: "black",
                        }),
                        vectorLayer,
                    ],
                    view: new View({
                        center: [118.1163, 24.4673],
                        zoom: 12,
                        projection: "EPSG:4326",
                    }),
                    // 使用 Vue 的 ref 来引用 DOM 元素
                    target: this.$refs.map,
                });
                this.map.addEventListener("click", this.MapClick);
            });
        },
        // 地图点击事件
        MapClick(e) {
            // console.log(e)
            let coordinate = e.coordinate;
            // console.log(coordinate);
            this.getGeocoderAddress(coordinate[0], coordinate[1]).then((res) => {
                this.mapForm.mapaddress = res.result.formatted_address;
            });
            // 创建一个新的图标要素
            this.mapForm.maplnglat = coordinate.join("/");
            let newIconFeature = new Feature({
                geometry: new Point(coordinate),
            });
            newIconFeature.setStyle(this.iconStyle);
            // 清除之前的图标要素
            this.vectorSource.clear();
            // 添加新的图标要素
            this.vectorSource.addFeature(newIconFeature);
        },
        // 根据地图坐标获取具体地址
        getGeocoderAddress(lon, lat) {
            return request({
                url: `/geocoder?postStr={'lon':${lon},'lat':${lat},'ver':1}&type=geocode&tk=${this.mapToken}`,
                method: "post",
                type: "map",
            });
        },
        // 地图搜索功能
        mapSearchFn() {
            let keyWord = this.mapForm.mapSearch;
            this.getGeocoderLonLat(keyWord).then((res) => {
                let newIconFeature = new Feature({
                    geometry: new Point([res.location.lon, res.location.lat]),
                });
                newIconFeature.setStyle(this.iconStyle);
                this.vectorSource.clear();
                // console.log(res.location.lon, res.location.lat);
                this.map.getView().setCenter([res.location.lon, res.location.lat]);
                this.map.getView().setZoom(12);
                // 添加新的图标要素
                this.vectorSource.addFeature(newIconFeature);
                this.mapForm.maplnglat = res.location.lon + "," + res.location.lat;
            });
        },
        // 根据地址获取对应的地图坐标
        getGeocoderLonLat(keyWord) {
            return request({
                url: `/geocoder?ds={'keyWord':"${keyWord}"}&tk=${this.mapToken}`,
                method: "post",
                type: "map",
            });
        },
        // 地图确定按钮
        mapSubmitForm() {
            let tempLonLatArr = this.mapForm.maplnglat;
            this.formModel.lng = tempLonLatArr.split("/")[0];
            this.formModel.lat = tempLonLatArr.split("/")[1];
            this.isVisibleMap = false;
        },
    },
    mounted() {
        EventBus.$on('currentTree', treeData => {
            // console.log('Received tree data:', treeData);
            this.searchMap.deptId = treeData.id
            this.projectPointId = treeData.projectPointId
            // this.formModel.projectPointId = treeData.projectPointId
            // 处理接收到的数据
            this.getList()
            this.getDeptTree()

        });

    },
}
</script>
<style lang="less">
.control {
    // .per_table {
    //     .el-table__cell {
    //         .cell {
    // overflow: hidden;
    // text-overflow: ellipsis;
    // white-space: nowrap;
    //         }
    //     }
    // }

    .table-span-color-box {
        width: 40px;
        height: 40px;
        text-align: center;
        display: inline-block;
    }
}
</style>
<style lang="less" scoped>
@dialog-height: 860px;

.basiceinformation-container {
    height: calc(@dialog-height - 230px);
    overflow: auto;

    .project-body {
        padding: 0 15px;
        height: 100%;
    }
}

// 天地图样式？
/deep/ .ol-zoom.ol-unselectable.ol-control {
    display: none;
}

/deep/ .ol-rotate.ol-unselectable.ol-control.ol-hidden {
    display: none;
}

/deep/ .map-Contern {
    .map-form {
        padding: 24px;

        .el-form-item--small.el-form-item {
            margin-bottom: 12px;
        }
    }

    .map-footer-btn {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        padding-bottom: 10px;
    }
}

/deep/ .map-Contern {
    position: absolute;
    top: 0;
    right: 0;
    background: rgba(19, 21, 26, 0.6);
}
</style>
<style lang="less" scoped></style>